/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistencia.controller.jpa;

import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import persistencia.controller.jpa.exceptions.NonexistentEntityException;
import persistencia.entidade.Categoria;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import persistencia.entidade.Registro;

/**
 *
 * @author Novo usuário
 */
public class RegistroJpaController implements Serializable{

    public RegistroJpaController() {
        
    }

    public EntityManager getEntityManager(){
        return JdbcController.getInstance().getEntityManager();
    }
    
    public void create(Registro registro) {
        if (registro.getCategoriaCollection() == null) {
            registro.setCategoriaCollection(new ArrayList<Categoria>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Categoria> attachedCategoriaCollection = new ArrayList<Categoria>();
            for (Categoria categoriaCollectionCategoriaToAttach : registro.getCategoriaCollection()) {
                categoriaCollectionCategoriaToAttach = em.getReference(categoriaCollectionCategoriaToAttach.getClass(), categoriaCollectionCategoriaToAttach.getCategoriaId());
                attachedCategoriaCollection.add(categoriaCollectionCategoriaToAttach);
            }
            registro.setCategoriaCollection(attachedCategoriaCollection);
            em.persist(registro);
            for (Categoria categoriaCollectionCategoria : registro.getCategoriaCollection()) {
                categoriaCollectionCategoria.getRegistroCollection().add(registro);
                categoriaCollectionCategoria = em.merge(categoriaCollectionCategoria);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

     public List<String> getCidadesDistinct(){
        EntityManager em = getEntityManager();
         try {
            Query q = em.createQuery("select distinct o.cidade from Registro as o");
            return q.getResultList();
        } finally {
            em.close();
        }
    }

      public List<String> getUFDistinct(){
        EntityManager em = getEntityManager();
         try {
            Query q = em.createQuery("select distinct o.uf from Registro as o");
            return q.getResultList();
        } finally {
            em.close();
        }
    }

       public List<String> getDDDDistinct(){
        EntityManager em = getEntityManager();
         try {
            Query q = em.createQuery("select distinct o.ddd from Registro as o");
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public void edit(Registro registro) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Registro persistentRegistro = em.find(Registro.class, registro.getRegistroId());
            List<Categoria> categoriaCollectionOld = persistentRegistro.getCategoriaCollection();
            List<Categoria> categoriaCollectionNew = registro.getCategoriaCollection();
            List<Categoria> attachedCategoriaCollectionNew = new ArrayList<Categoria>();
            for (Categoria categoriaCollectionNewCategoriaToAttach : categoriaCollectionNew) {
                categoriaCollectionNewCategoriaToAttach = em.getReference(categoriaCollectionNewCategoriaToAttach.getClass(), categoriaCollectionNewCategoriaToAttach.getCategoriaId());
                attachedCategoriaCollectionNew.add(categoriaCollectionNewCategoriaToAttach);
            }
            categoriaCollectionNew = attachedCategoriaCollectionNew;
            registro.setCategoriaCollection(categoriaCollectionNew);
            registro = em.merge(registro);
            for (Categoria categoriaCollectionOldCategoria : categoriaCollectionOld) {
                if (!categoriaCollectionNew.contains(categoriaCollectionOldCategoria)) {
                    categoriaCollectionOldCategoria.getRegistroCollection().remove(registro);
                    categoriaCollectionOldCategoria = em.merge(categoriaCollectionOldCategoria);
                }
            }
            for (Categoria categoriaCollectionNewCategoria : categoriaCollectionNew) {
                if (!categoriaCollectionOld.contains(categoriaCollectionNewCategoria)) {
                    categoriaCollectionNewCategoria.getRegistroCollection().add(registro);
                    categoriaCollectionNewCategoria = em.merge(categoriaCollectionNewCategoria);
                }
            }
            em.flush();
            em.getTransaction().commit();
            
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = registro.getRegistroId();
                if (findRegistro(id) == null) {
                    throw new NonexistentEntityException("The registro with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Registro registro;
            try {
                registro = em.getReference(Registro.class, id);
                registro.getRegistroId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The registro with id " + id + " no longer exists.", enfe);
            }
            List<Categoria> categoriaCollection = registro.getCategoriaCollection();
            for (Categoria categoriaCollectionCategoria : categoriaCollection) {
                categoriaCollectionCategoria.getRegistroCollection().remove(registro);
                categoriaCollectionCategoria = em.merge(categoriaCollectionCategoria);
            }
            em.remove(registro);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Registro> findRegistroEntities() {
        return findRegistroEntities(true, -1, -1);
    }

    public List<Registro> findRegistroEntitiesSemCategoria() {
        List<Registro> regs = findRegistroEntities(true, -1, -1);
        List<Registro> regsReturn = new ArrayList<Registro>();
        for (Iterator<Registro> it = regs.iterator(); it.hasNext();) {
            Registro registro = it.next();
            if (registro.getCategoriaCollection().size() == 0) {
                regsReturn.add(registro);
            }
        }
        return regsReturn;
    }

    public List<Registro> findRegistroEntities(int maxResults, int firstResult) {
        return findRegistroEntities(false, maxResults, firstResult);
    }

    private List<Registro> findRegistroEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Registro as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Registro findRegistro(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Registro.class, id);
        } finally {
            em.close();
        }
    }

    public int getRegistroCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Registro as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
